var NetCopy, Utils, refSettings, curSettings, xul, curListbox, curSettingId, curSettingIndex, contentEdited;

function onLoad(){
	NetCopy = window.arguments[0];
	Utils = NetCopy.Utils;
	refSettings = window.arguments[1];
	bakSettings = Utils.clone(refSettings);
	curSettings = Utils.clone(refSettings);
	enable_tab_character('#templates textbox[multiline]');
	
	xul = {
		tabs: document.getElementById("tabs"),
		panels: document.getElementById("panels"),
		listboxes: {
			filters : document.getElementById("filters-listbox"),
			templates : document.getElementById("templates-listbox"),
		}
	};
	
	xul.tabs.selectedIndex = curSettings.tabIndex;
	xul.tabs.addEventListener('select', on_tab_select);
	xul.panels.addEventListener('change', function(){ contentEdited=true; });
	bind_inputs(curSettings.filters[0]);
	bind_inputs(curSettings.templates[0]);
	curSettingId = xul.panels.selectedPanel.id;
	curListbox = xul.listboxes[curSettingId];
	display_settings(curSettings);
}

function display_settings(settings){
	fill_listbox(xul.listboxes.templates, settings.templates, settings.templateIndex);
	fill_listbox(xul.listboxes.filters, settings.filters, settings.filterIndex);
	curSettingIndex =  xul.listboxes[curSettingId].selectedIndex;
	display_dataset(settings[curSettingId][curSettingIndex]);
}

function fill_listbox(listbox, settings, selectedIndex){
	listbox.removeEventListener('select', on_listbox_select);
	listbox.clearSelection();
	while(listbox.itemCount)
		listbox.removeItemAt(0);
	for (var i = 0; i < settings.length; i++) {
		var listitem = document.createElement('listitem');
		listitem.setAttribute('label', settings[i].name);
		listitem.initialIndex = i;
		listbox.appendChild(listitem);
	}
	listbox.selectedIndex = selectedIndex;
	listbox.addEventListener('select', on_listbox_select);
}

function enable_tab_character(query){
	var fntab = function(ev) {
        if(ev.keyCode==9 && !ev.shiftKey) {
			ev.preventDefault();
			var pos=this.selectionStart;
			this.value=this.value.substr(0,pos)+'\t'+this.value.substr(pos);
			this.selectionStart=this.selectionEnd=pos+1;
			var ev_change = document.createEvent("HTMLEvents");
			ev_change.initEvent("change", false, true);
			this.dispatchEvent(ev_change);
        }
	};
	Array.forEach(document.querySelectorAll(query), function(e){ e.addEventListener( 'keypress', fntab);});
}

function on_tab_select(event){
	curSettingId = xul.panels.selectedPanel.id;
	curListbox = xul.listboxes[curSettingId];
	curSettingIndex = curListbox.selectedIndex;
	display_dataset(curSettings[curSettingId][curSettingIndex]);
}

function on_listbox_dragstart(event){
	var dt = event.dataTransfer;
	dt.effectAllowed = dt.dropEffect = "move";
	dt.mozSetDataAt("listitem/index", event.target.parentNode.getIndexOfItem(event.target), 0);
}

function on_listbox_dragover(event){
	if(event.target.tagName == "listitem" && event.dataTransfer.types.contains("listitem/index"))
		event.preventDefault();
}

function on_listbox_drop(event){
	var dragIndex = event.dataTransfer.mozGetDataAt("listitem/index", 0);
	var dropIndex = curListbox.getIndexOfItem(event.target);
	doMove(dragIndex, dropIndex);
	event.preventDefault();
}

function on_listbox_select(event){
	if(curListbox.suppressOnSelect)
		return;
	setTimeout( function(){	//to process the change events before this one
		curSettingIndex = event.target.selectedIndex;
		if(curSettingIndex != -1)
			display_dataset(curSettings[curSettingId][curSettingIndex]);
	}, 0);
}

function on_listbox_keypress(event){
	var charCode = event.charCode;
	var keyCode = event.keyCode;
	if(keyCode === 46)	//Del key
		doDelete();
	else if(charCode === 114 || charCode === 82) // R, r key
		doRename();	
	else if(charCode === 100 || charCode === 68)	// D, d key
		doDuplicate();
}


var field_writers = {};

function display_dataset(settings){
	for(var pref of Utils.objfields(settings)){
		if(pref in field_writers)
			field_writers[pref](settings[pref]);
	}
}

function bind_inputs(dataset){
	for(var id of Utils.objfields(dataset)){
		var input = document.getElementById(id);
		if(input)
			bind_input(id, input, dataset[id]);
	}
}

function bind_input(id, input, value){
	var type =  typeof value;
	if(Array.isArray(value)){
		input.addEventListener('change', function(ev){
			curSettings[curSettingId][curSettingIndex][id] = ev.target.value.trim().match(/[^ \r\n][^\r\n]*(?! )/g) || [];
		});
		field_writers[id] = function(data){
			input.value = data.length ? data.join('\n') + '\n' : '';
		};
	}else if(type  === "boolean"){
		input.addEventListener('click', function(ev){
			curSettings[curSettingId][curSettingIndex][id] = ev.target.checked ? true : false;
		});
		field_writers[id] = function(data){
			input.checked = data;
		};
	}else if(type  === "object"){
		input.addEventListener('change', function(ev){
			var txt = ev.target.value.trim();
			var newobj = {};
			var m, re = new RegExp(/^([^:]+):(.+$)/mg);
			while ((m = re.exec(txt)) !== null)
				newobj[m[1].trim()] = m[2].trim();
			curSettings[curSettingId][curSettingIndex][id] = newobj;
		});
		field_writers[id] = function(data){
			input.value = Utils.objmap(data, function(k,v){return k + ': ' + v + '\n';}).join('');
		};
	}else{
		input.addEventListener('change', function(ev){
			curSettings[curSettingId][curSettingIndex][id] = (ev.target.value || '').replace(/\\n/g, '\n').replace(/\\t/g, '\t');
		});
		if(input.getAttribute('multiline')){
			field_writers[id] = function(data){
				input.value = data;
			};
		}else{
			field_writers[id] = function(data){
				input.value = data.replace(/\n/g, '\\n').replace(/\t/g, '\\t');
			};
		}
	}
}

function doMove(indexFrom, indexTo){
	curListbox.suppressOnSelect = true;
	curListbox.insertBefore(curListbox.childNodes[indexFrom], curListbox.childNodes[ indexTo + (indexTo >= indexFrom) ]);
    curSettings[curSettingId].splice(indexTo, 0, curSettings[curSettingId].splice(indexFrom, 1)[0]);
	curListbox.selectedIndex = curSettingIndex = indexTo;
	contentEdited = true;
	curListbox.suppressOnSelect = false;
}

function doInsert(inputid, ref){
	var input = document.getElementById(inputid);
	var start=input.selectionStart;
	var end=input.selectionEnd;
	input.value=input.value.substr(0,start) + ref + input.value.substr(end);
	input.selectionStart = input.selectionEnd = start + ref.length;
	var ev_change = document.createEvent("HTMLEvents");
	ev_change.initEvent("change", false, true);
	input.dispatchEvent(ev_change);
}

function doRename(){
	var name = window.prompt("Enter a new name:", curListbox.currentItem.label);
	if(!name)
		return;
	contentEdited = true;
	curListbox.currentItem.label = name;
	curSettings[curSettingId][curSettingIndex].name = name;
}

function doReload(){
	contentEdited = true;
	display_dataset( curSettings[curSettingId][curListbox.selectedIndex] = Utils.clone(bakSettings[curSettingId][curListbox.currentItem.initialIndex]) );
}

function doDuplicate(){
	contentEdited = true;
	curListbox.suppressOnSelect = true;
	var ds = Utils.clone(curSettings[curSettingId][curSettingIndex]);
	ds.name = Utils.get_unique_name( ds.name, curSettings[curSettingId].map(function(e){return e.name;}) );
	curSettings[curSettingId].push( ds );
	var li = document.createElement('listitem');
	li.setAttribute('label', ds.name);
	li.initialIndex = curListbox.currentItem.initialIndex;
	curListbox.appendChild(li);
	curListbox.selectedIndex = curSettingIndex = curListbox.itemCount - 1;
	curListbox.suppressOnSelect = false;
}

function doDelete(){
	if(curListbox.itemCount < 2)
		return;
	contentEdited = true;
	curSettings[curSettingId].splice(curSettingIndex, 1);
	curListbox.suppressOnSelect = true;
	curListbox.clearSelection();
	curListbox.removeItemAt(curSettingIndex);
	curListbox.suppressOnSelect = false;
	curListbox.selectedIndex = curSettingIndex = Math.min(curSettingIndex, curListbox.itemCount -1);
}

function doReset(){
	contentEdited = true;
	curSettings.reset();
	display_settings(curSettings);
}

function doImport(){
	try{
		var text = Utils.get_text_filepicker(window);
		if(text){
			var object = JSON.parse(text);
			contentEdited = true;
			curSettings.merge(object);
			bakSettings = Utils.clone(curSettings);
			display_settings(curSettings);
		}
	}catch(ex){
		alert('Error: ' + ex.message + '\n' + ex.trace);
	}
}

function doExport(){
	var text = JSON.stringify( { filters: curSettings.filters, templates: curSettings.templates }, null, '  ');
	Utils.save_text_filepicker(window, text);
}

function doSave(){
	curSettings.tabIndex = xul.tabs.selectedIndex;
	curSettings.filterIndex = xul.listboxes.filters.selectedIndex;
	curSettings.templateIndex = xul.listboxes.templates.selectedIndex;
	refSettings.update(curSettings);
	refSettings.save(contentEdited);
	window.close();
}

function doCancel(){
  window.close();
}
